using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//
using System.Linq.Expressions;
using DbFrame.SQLContext;
using DbFrame.Class;
using DbFrame.AdoDotNet;
using System.Data;
using System.Data.Common;
using DbFrame.SQLContext.Interface;

namespace DbFrame
{
    public class DBContext : IAdd, IEdit, IDelete, IFind
    {
        public string ErrorMessge = string.Empty;
        protected AddContext add;
        protected EditContext edit;
        protected DeleteContext delete;
        protected FindContext find;
        protected CheckContext<BaseEntity> check;
        public DbHelper dbhelper;

        private string _ConnectionString { get; set; }

        private DataBaseType DbType { get; set; }

        /// <summary>
        /// 数据库操作类
        /// </summary>
        /// <param name="ConnectionString">链接串 不传入默认为 ConnectionString </param>
        public DBContext(DataBaseType dbtype = DataBaseType.MsSql, string ConnectionString = null)
        {
            if (string.IsNullOrEmpty(ConnectionString))
                _ConnectionString = ConfigModel.SqlServer;
            else
                _ConnectionString = ConnectionString;
            add = new AddContext(_ConnectionString, dbtype);
            edit = new EditContext(_ConnectionString, dbtype);
            delete = new DeleteContext(_ConnectionString, dbtype);
            find = new FindContext(_ConnectionString, dbtype);
            dbhelper = new DbHelper(_ConnectionString, dbtype);
            check = new CheckContext<BaseEntity>(_ConnectionString, dbtype);
            DbType = dbtype;
        }

        /// <summary>
        /// 设置错误消息
        /// </summary>
        /// <param name="Error"></param>
        private void SetError(string Error)
        {
            ErrorMessge = string.Empty;
            ErrorMessge = Error.Replace("\r\n", "<br />");
        }

        /// <summary>
        /// 验证实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CheckModel<T>(T model) where T : BaseEntity, new()
        {
            try
            {
                if (!check.Check(model))
                    throw new Exception(check.ErrorMessage);
                return true;
            }
            catch (Exception ex)
            {
                this.SetError(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 验证实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private void Check<T>(T model) where T : BaseEntity, new()
        {
            if (!check.Check(model))
                throw new Exception(check.ErrorMessage);
        }

        /// <summary>
        /// 将datarow 转换为Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public T DataRowToModel<T>(DataRow dr) where T : BaseEntity, new()
        {
            return DbHelper.ToModel<T>(dr);
        }

        /// <summary>
        /// Json 转换为 List <T>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Json"></param>
        /// <returns></returns>
        public List<T> JsonToList<T>(string Json)
        {
            return ModelExFunc.DeserializeObject<List<T>>(Json);
        }


        /********************************************************/
        /************************数据库操作
        /********************************************************/

        public object Add<T>(T Model, bool IsCheck = false) where T : BaseEntity, new()
        {
            try
            {
                if (IsCheck)
                    this.Check(Model);
                var key = add.Add<T>(Model).To_String();
                if (string.IsNullOrEmpty(key))
                    throw new Exception("操作失败");
                return key;
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return string.Empty;
            }
        }

        public object Add<T>(Expression<Func<T>> Func) where T : BaseEntity, new()
        {
            try
            {
                var key = add.Add<T>(Func).To_String();
                if (string.IsNullOrEmpty(key))
                    throw new Exception("操作失败");
                return key;
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return string.Empty;
            }
        }

        public object Add<T>(T Model, List<SQL> li, bool IsCheck = false) where T : BaseEntity, new()
        {
            try
            {
                if (IsCheck)
                    this.Check(Model);
                var key = add.Add<T>(Model, li).To_String();
                if (string.IsNullOrEmpty(key))
                    throw new Exception("操作失败");
                return key;
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return string.Empty;
            }
        }

        public object Add<T>(Expression<Func<T>> Func, List<SQL> li) where T : BaseEntity, new()
        {
            try
            {
                var key = add.Add<T>(Func, li).To_String();
                if (string.IsNullOrEmpty(key))
                    throw new Exception("操作失败");
                return key;
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return string.Empty;
            }
        }

        public bool Edit<T>(T Set, Expression<Func<T, bool>> Where, bool IsCheck = false) where T : BaseEntity, new()
        {
            try
            {
                if (IsCheck)
                    this.Check(Set);
                if (edit.Edit(Set, Where))
                    return true;
                throw new Exception("操作失败");
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return false;
            }
        }

        public bool Edit<T>(Expression<Func<T>> Set, Expression<Func<T, bool>> Where) where T : BaseEntity, new()
        {
            try
            {
                if (edit.Edit(Set, Where))
                    return true;
                throw new Exception("操作失败");
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return false;
            }
        }

        public bool Edit<T>(T Set, Expression<Func<T, bool>> Where, List<SQL> li, bool IsCheck = false) where T : BaseEntity, new()
        {
            try
            {
                if (IsCheck)
                    this.Check(Set);
                if (edit.Edit(Set, Where, li))
                    return true;
                throw new Exception("操作失败");
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return false;
            }
        }

        public bool Edit<T>(Expression<Func<T>> Set, Expression<Func<T, bool>> Where, List<SQL> li) where T : BaseEntity, new()
        {
            try
            {
                if (edit.Edit(Set, Where, li))
                    return true;
                throw new Exception("操作失败");
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return false;
            }
        }

        public bool Delete<T>(Expression<Func<T, bool>> Where) where T : BaseEntity, new()
        {
            try
            {
                if (delete.Delete<T>(Where))
                    return true;
                throw new Exception("操作失败");
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return false;
            }
        }

        public bool Delete<T>(Expression<Func<T, bool>> Where, List<SQL> li) where T : BaseEntity, new()
        {
            try
            {
                if (delete.Delete<T>(Where, li))
                    return true;
                throw new Exception("操作失败");
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return false;
            }
        }

        public IQuery Find()
        {
            return find.Find();
        }

        public DataTable Find(string SQL)
        {
            return find.Find(SQL);
        }

        public object FindObject(string SQL)
        {
            return find.FindObject(SQL);
        }

        public T Find<T>(Expression<Func<T, bool>> Where) where T : BaseEntity, new()
        {
            return find.Find<T>(Where);
        }

        public DataTable FindTable<T>(Expression<Func<T, bool>> Where, string OrderBy = "") where T : BaseEntity, new()
        {
            return find.FindTable<T>(Where, OrderBy);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Where"></param>
        /// <param name="OrderBy"></param>
        /// <returns></returns>
        public List<T> FindList<T>(Expression<Func<T, bool>> Where, string OrderBy = "") where T : BaseEntity, new()
        {
            return find.FindList<T>(Where, OrderBy);
        }

        /// <summary>
        /// 根据 DataTable 得到 List<T>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public List<T> FindListByTable<T>(DataTable dt) where T : BaseEntity, new()
        {
            return find.FindListByTable<T>(dt);
        }

        /// <summary>
        /// 根据 sql 语句 得到 List<Dictionary<string, object>>
        /// </summary>
        /// <param name="SQL"></param>
        /// <returns></returns>
        public List<Dictionary<string, object>> FindList(string SQL)
        {
            return find.FindList(SQL);
        }

        /// <summary>
        /// 根据 DataTable 得到 List<Dictionary<string, object>>
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public List<Dictionary<string, object>> FindList(DataTable dt)
        {
            return find.FindList(dt);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="orderField"></param>
        /// <param name="isAsc"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="dbParameter"></param>
        /// <returns></returns>
        public PagingEntity Find(string strSql, string orderField, bool isAsc, int pageIndex, int pageSize, DbParameter[] dbParameter = null)
        {
            return find.Find(strSql, orderField, isAsc, pageIndex, pageSize, dbParameter);
        }

        /// <summary>
        /// 获取自增 编号
        /// </summary>
        /// <param name="TabName"></param>
        /// <param name="FieldNum"></param>
        /// <returns></returns>
        public int GetNumber(string TabName, string FieldNum)
        {
            return find.GetNumber(TabName, FieldNum);
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        /// <returns></returns>
        public bool Commit(List<SQL> li)
        {
            try
            {
                if (dbhelper.Commit(li))
                    return true;
                throw new Exception("操作失败");
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        /// <returns></returns>
        public bool Commit(List<SQL> li, Action<int, SQL, System.Data.Common.DbCommand> callBack)
        {
            try
            {
                if (dbhelper.Commit(li, callBack))
                    return true;
                throw new Exception("操作失败");
            }
            catch (Exception ex)
            {
                SetError(ex.Message);
                return false;
            }
        }


    }
}
